import pdfplumber
import os

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def convert_pdf_to_image_v2(pdf_path, image_path):
    logger.info(f'正在处理文件 {pdf_path}')
    with pdfplumber.open(pdf_path) as pdf:
        for i, page in enumerate(pdf.pages):
            print(f'正在处理第 {i + 1} 页', end='\r')
            image = page.to_image(resolution=150)
            image_path_full = os.path.join(image_path, f'{i + 1}.png')
            image.save(image_path_full)


# # 使用示例
# pdf_path = 'example.pdf'
# image_path = './images_v2'
# convert_pdf_to_image_v2(pdf_path, image_path)
if __name__ == '__main__':
    import argparse
    from pathlib import Path

    parser = argparse.ArgumentParser()
    # ask for folder path
    parser.add_argument(
        'folder_path', type=str,
        help='folder path containing pdf files')
    args = parser.parse_args()
    folder_path_str = args.folder_path
    folder_path = Path(folder_path_str)
    for file in folder_path.glob('*.pdf'):
        image_out_dir = folder_path / file.stem
        image_out_dir.mkdir(exist_ok=True)
        convert_pdf_to_image_v2(file, image_out_dir)
